package com.xiaouyudeguang.common.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.xiaouyudeguang.common.interceptor.MybatisSqlInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Configuration
@Slf4j
public class MyBatisInterceptorConfig {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @PostConstruct
    public void addInterceptor() {
        List<Interceptor> interceptors = sqlSessionFactory.getConfiguration().getInterceptors();
        MybatisPlusInterceptor mybatisPlusInterceptor = null;
        for (Interceptor interceptor : interceptors) {
            if (interceptor instanceof MybatisPlusInterceptor) {
                mybatisPlusInterceptor = (MybatisPlusInterceptor) interceptor;
            }
            break;
        }
        if (mybatisPlusInterceptor == null) {
            return;
        }
        List<InnerInterceptor> newArray = new ArrayList<>();
        List<InnerInterceptor> innerInterceptorList = mybatisPlusInterceptor.getInterceptors();
        for (InnerInterceptor innerInterceptor : innerInterceptorList) {
            if (innerInterceptor instanceof PaginationInnerInterceptor) {
                newArray.add(new MybatisSqlInterceptor());
            }
            newArray.add(innerInterceptor);
        }
        mybatisPlusInterceptor.setInterceptors(newArray);
    }
}
